<?php
namespace Common\Model;

/**
 * 管理员模型
 * @author Administrator
 *
 */
class UserModel extends CommModel {
	
	// 用户表自动验证
	protected $_validate = array (
			// 帐号长度不合法
			array ( 'username', '/^[^@]{2,20}$/i', '帐号长度不合法！', self::EXISTS_VALIDATE ),
			// 密码长度不合法
			array ( 'password', '6,30', '密码长度不合法！', self::EXISTS_VALIDATE, 'length' ),
			// 验证码错误
			array ( 'verify', 'checkVerify', "验证码错误", self::EXISTS_VALIDATE, 'function' ) 
	);
	
	// 用户表自动完成
	protected $_auto = array (
			array ( 'password', 'sha1', self::MODEL_BOTH, 'function' ),
			array ( 'create_time', 'time', self::MODEL_INSERT, 'function' ) 
	);

	/**
	 * 登录用户
	 *
	 * @param string $username 用户名
	 * @param string $password 密码
	 * @param string $verify 验证码
	 * @return string Ambigous
	 */
	public function login($username, $password, $verify) {
		$data = array ( 'username' => $username, 'password' => $password, 'verify' => $verify );
		
		// where条件
		$map = array ();
		
		if (! $this->create ( $data )) {
			return $this->getError ();
		} else {
			$map ['username'] = $username;
			$user = $this->field ( "id,auth,username,password,nickname" )->where ( $map )->find ();
			
			if ($user ['password'] == sha1 ( $password )) {
				// 更新登录信息
				$update = array (
						'id' => $user ['id'],
						'last_login_time' => time (),
						'last_login_ip' => get_client_ip ( 1 ) 
				);
				$this->save ( $update );
				
				// 更新登录日志
				$this->addLog ( $username, $password, $update ['last_login_time'], '登录成功' );
				
				// 写入到session
				$auth = array (
						'id' => $user ['id'],
						'auth' => $user ['auth'],
						'username' => $user ['username'],
						'nickname' => $user ['nickname'],
						'last_login_time' => $update ['last_login_time'],
						'last_login_ip' => $update ['last_login_ip'] 
				);
				session ( 'userAuth', $auth );
				return $user ['id'];
			} else {
				// 更新登录日志
				$this->addLog ( $username, $password, time (), '登录失败' );
				return "用户名或密码错误";
			}
		}
	}

	/**
	 * 登录日志添加
	 *
	 * @param string $username 登录用户名
	 * @param string $password 登录密码
	 * @param string $lastTime 登录时间
	 * @param string $remark 备注
	 */
	private function addLog($username, $password, $lastTime, $remark) {
		$log = array (
				'username' => $username,
				'password' => $password,
				'ip' => get_client_ip ( 1 ),
				'create_time' => $lastTime,
				'system' => getSystem (),
				'browser' => getBrowser (),
				'remark' => $remark 
		);
		D ( 'UserLog' )->add ( $log );
	}
	
	/**
	 * 密码修改
	 * 
	 * @param array $data
	 */
	public function pass_edit( $data ) {
		if ($this->create ( $data )) {
			$return = $this->getCommOne ( $data ['id'] );
			if ($return ['status']) {
				$data['password'] = sha1( $data['password'] );
				$this->save ( $data );
				$return ['info'] = '操作成功!';
			}
		} else {
			$return['status'] = 0;
			$return['info'] = $this->getError();
		}
		return $return;
	}
}